const express = require("express");
const cors = require("cors");
const bodyParser = require("body-parser");
const multer = require("multer");
const path = require("path");
const { db, genid } = require("./db/index");

const app = express();
app.use(cors());
app.use(express.urlencoded({ extended: false }));
app.use(bodyParser.json());
// 指定静态资源路径
app.use(express.static(path.join(__dirname, "public")));

const update = multer({
  dest: "./public/upload/temp",
});
app.use(update.any());

// 登录权限验证
const ADMIN_TOKEN_PATH = "/_token";
app.all("*", async (req, res, next) => {
  if (req.path.indexOf(ADMIN_TOKEN_PATH) > -1) {
    // console.log('有token')
    let token = req.headers.token;
    if(!token){
      res.json({
        code: 403,
        msg: "请先登录",
      });
      return;
    }
    // console.log(token)
    let admin_token_sql = "select * from admin where token = ?";
    let admin_result = await db.async.query(admin_token_sql, token);
    // console.log(admin_result)
    if (admin_result.results.length == 0 || admin_result.err != null) {
      res.json({
        code: 403,
        msg: "请先登录",
      });
      return;
    } else {
      next();
    }
  } else {
    next();
  }
});

const testRouter = require("./routers/TestRouter");
app.use("/test", testRouter);

const adminRouter = require("./routers/admin");
app.use("/admin", adminRouter);

const categoryRouter = require("./routers/category");
app.use("/category", categoryRouter);

const blogRouter = require("./routers/blog");
app.use("/blog", blogRouter);

const uploadRouter = require("./routers/upload");
app.use("/upload", uploadRouter);

app.listen(3030, () => {
  console.log("Server is running at http://127.0.0.1:3030");
});
